<?php
declare (strict_types = 1);

namespace app\controller\admin;

use app\model\Article;
use think\facade\Validate;
use think\response\Json;

class AdminArticle extends AdminBase
{

	protected $middleware = [
		'app\middleware\AdminLogin',
		'app\middleware\AdminAuth' => [
            'except' => ['parent']
        ]
	];

	private string $menuName = '文章管理';

    /**
     * 显示资源列表
     * @throws
     * @return Json
     */
    public function index():Json
    {
        $limit = input('pageSize/d',10);

		//分页配置
		$pageConfig = ['list_rows'=>$limit,'var_page'=>'pageNum'];

        $acc = new AdminArticleClassify($this->app);
        $options = $acc->getParent(0,-1,'id,id as value,name as label');
        //搜索字段配置
        $search = [
			[
				'label'=>'文章标题',//标签
				'prop'=> 'title',//表单名称
				'field' => 'title|writer|desc',//查询字段
				'placeholder'=> '模糊搜索标题|作者|简述',
				'required'=> false,//是否必填
				'expression' => 'like',//查询表达式：like,not like,in,not in,between,not between,null,not null,time,>,<,>=,<=,=,<>(!=),find(FIND_IN_SET)
				'type'=> 'input',//类型：input,select,date,datetime,year,month,week,datetimerange,daterange
                'typeof' => 's',//强制转换类型：d整数，a数组，s字符串，b布尔类型，f浮点数
			],
            [
                'label'=>'文章分类',//标签
                'prop'=> 'aid',//表单名称
                'field' => 'article_classify_id',//查询字段
                'placeholder'=> '选择文章分类',
                'required'=> false,//是否必填
                'expression' => '=',//查询表达式：like,not like,in,not in,between,not between,null,not null,time,>,<,>=,<=,=,<>(!=),find(FIND_IN_SET)
                'type'=> 'cascader',//类型：input,select,cascader,date,datetime,year,month,week,datetimerange,daterange
                'typeof' => 'd',//强制转换类型：d整数，a数组，s字符串，b布尔类型，f浮点数
                'options' => $options
            ],
            [
                'label'=>'类型',//标签
                'prop'=> 'type',//表单名称
                'field' => 'type',//查询字段
                'placeholder'=> '选择类型',
                'required'=> false,//是否必填
                'expression' => '=',//查询表达式：like,not like,in,not in,between,not between,null,not null,time,>,<,>=,<=,=,<>(!=),find(FIND_IN_SET)
                'type'=> 'select',//类型：input,select,date,datetime,year,month,week,datetimerange,daterange
                'typeof' => 'd',//强制转换类型：d整数，a数组，s字符串，b布尔类型，f浮点数
                'options' => [//下拉选项
                    [ 'label'=> '列表', 'value'=> 1 ],
                    [ 'label'=> '单页', 'value'=> 2 ],
                ]
            ],
		];

		$map = [];
		$this->setMap($search,$map);

		$data = Article::with(['c'])
            ->where($map)
			->order('create_time','desc')
			->paginate($pageConfig)
            ->each(function ($item){
                $item['is_del'] = $item['type'] === 2?1:0;
                //$item['type'] = $item['type'] === 1 ? '列表' : '单页';
                return $item;
            });

		$this->result['data'] = [
			'total' => $data->total(),
			'data' => $data->items(),
			'search' => $search
		];
		return returnAdmin($this->request,$this->result,$this->menuName.'-列表',$this->adminInfo);
    }

    /**
	 * 保存编辑的资源
	 * @throws
	 * @return Json
	 */
	public function save():Json
	{
		//获取form表单
		$param = input('param.',[]);

		$param = toUnderline($param);

		try{

			$model = new Article();
			$fields = $model->getFields();
			$pk = $model->getPk();
			$id = $param[$pk] ?? 0;
			$rule = [
				'title' => 'require|max:255',
				'detail' => 'require',
			];
			$message = [
				'title.require' => '标题必填',
				'title.max' => '标题最多255个字符',
				'detail.require' => '详情必填'
			];
			$validate = Validate::rule($rule)->message($message);

			if(!$validate->check($param)){
				throw new \Exception($validate->getError());
			}

			if(!$id){
				//新增
				$model->create($param,$fields);
			}else{
				//修改
				$info = $model->find($id);
				if(!$info){
					throw new \Exception('无效参数');
				}
                unset($fields['type']);
                $cover = $info->getData('cover');
                $video = $info->getData('video');

				$info->allowField($fields)->save($param);

                //删除旧的视频文件
                if($video && $video != removeDomain($param['video'])){
                    if(is_file('.'.$video)){
                        @unlink('.'.$video);
                    }
                }
                //删除旧的图片文件
                if($cover && $cover != removeDomain($param['cover'])){
                    if(is_file('.'.$cover)){
                        @unlink('.'.$cover);
                    }
                }
			}

		}catch (\Exception $e){
			$this->result['code'] = 500;
			$this->result['msg'] = $e->getMessage();
		}
		return returnAdmin($this->request,$this->result,$this->menuName.'-编辑',$this->adminInfo);
	}



    /**
     * 删除指定资源
     * @throws
     * @return Json
     */
    public function delete():Json
    {

        $id = (string) input('id','');
        $ids = explode(',',$id);
        try {
            if (count($ids) > 1) {
                //批量删除
                Article::destroy($ids);
            } else {
                //指定id删除
                $info = Article::find($id);
                if (!$info) {
                    throw new \Exception('无效参数');
                }
                $cover = removeDomain($info['cover']);
                $video = removeDomain($info['video']);
                $info->delete();
                //其他处理
                //删除旧的视频文件
                if(is_file('.'.$video)){
                    @unlink('.'.$video);
                }
                //删除旧的图片文件
                if(is_file('.'.$cover)){
                    @unlink('.'.$cover);
                }

            }
            $this->result['msg'] = '删除ID：'.$id;
        }catch (\Exception $e){
            $this->result['code'] = 500;
            $this->result['msg'] = $e->getMessage();
        }

        return returnAdmin($this->request,$this->result,$this->menuName.'-删除',$this->adminInfo);
    }

}
